package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.constant.RabbitConstant;
import com.atguigu.tingshu.model.account.UserAccount;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * ClassName: AccountReciver
 * Package: com.atguigu.tingshu.account.receiver
 * Description:
 */
@Slf4j
@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听初始化账户的消息
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitConstant.ACCOUNT_INIT_QUEUE)
    @SneakyThrows
    public void addAccount(Message message, Channel channel) {
        //获取消息编号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //获取用户id
            long userId = Long.parseLong(new String(message.getBody()));

            //幂等性处理,判断用户账户是否存在
            UserAccount userAccount =
                    userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
            if (userAccount!=null) {
                //账户存在,直接应答
                channel.basicAck(deliveryTag, false);
                return;
            }
            //账户不存在为用户初始化账户
            Integer i = userAccountService.initAccount(userId);
            if (i < 0) {
                //创建失败
                throw new GuiguException(201,"新增账户失败");
            }
            //创建完成应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().getRedelivered()) {
                //todo:消息投递两次任然执行失败,后续处理
                log.error("消息投递两次任然执行失败,后续处理,丢掉");
                channel.basicReject(deliveryTag,false);
            }else {
                //第一次执行失败,消息重新投递
                log.error("第一次执行失败,消息重新投递");
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
